package com.yjc.springcloud.lb.Impl;

import com.yjc.springcloud.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shkstart
 * @create 2022-07-22 22:35
 */
@Component
public class LoadBalancerImpl implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private final int getAndIncrement() {
        int current;
        int next;

        do {
            current = atomicInteger.get();
            next = current > Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("第 " + next + " 次访问");
        return next;
    }

    private int getIndex(int len) {
        return getAndIncrement() % len;
    }


    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> instances) {
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        int index = getIndex(instances.size());
        return instances.get(index);
    }
}
